/* Copyright (c) 2011 Glenn Ganz
 
 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */

#import "CSJavaScript.h"
#import "CSObjectTemplate.h"
#import "CSArgument.h"
#import "v8.h"

id convertV8ToObjCObject(v8::Local<v8::Value> v8Obj, CSType type);
v8::Handle<v8::Value> convertObjCObjectToV8(id obj);

@interface CSScriptEngine(Private)

- (CSObjectTemplate*) globalTemplate;

@end

@interface CSJavaScriptHandle : NSObject
{
    v8::Handle<v8::Script> script;
}

- initWithString:(v8::Handle<v8::String>)string fileName:(NSString *)aFileName;
- (v8::Handle<v8::Script>)script;

@end

@implementation CSJavaScriptHandle

- initWithString:(v8::Handle<v8::String>)string fileName:(NSString *)aFileName
{
    v8::TryCatch try_catch;
    script = v8::Script::Compile(string, v8::String::New([aFileName fileSystemRepresentation]));
    if (script.IsEmpty()) {
        v8::String::AsciiValue error(try_catch.Exception());
        [NSException raise:@"CSJavaScriptException" format:@"Compilation error [%s] in script [%@]", *error, aFileName];
    }
    return self;
}

- (v8::Handle<v8::Script>)script
{
    return script;
}

@end

@interface CSJavaScript(Private)
- (id)_run;
@end

@implementation CSJavaScript(Private)


- (id)_run
{
    
    if (handle == nil) {
        v8::Handle<v8::String> str = v8::String::New((char *)[content bytes], [content length]);
        handle = [[CSJavaScriptHandle alloc] initWithString:str fileName:name];
    }
    
    v8::TryCatch try_catch;
    v8::Local<v8::Value> result = [handle script]->Run();
    if (result.IsEmpty()) {
        v8::String::AsciiValue error(try_catch.Exception());
        [NSException raise:@"CSJavaScriptException" format:@"Runtime error [%s] on line [%d]", *error, try_catch.Message()->GetLineNumber()];        
    } 
    else {
        if (!result->IsUndefined()) {
            return convertV8ToObjCObject(result, CSObject);
        }
        else {
            return nil;
        }
    }
    
    return nil;
}

@end


@implementation CSJavaScript


- initWithEngine:(CSScriptEngine *)aEngine fileName:(NSString *)aFileName
{    
    NSData *data = [NSData dataWithContentsOfFile:aFileName];
    if (data == nil) {
        [self release];
        [NSException raise:@"CSJavaScriptException" format:@"Script [%@] not found", aFileName];
    }
    
    return [self initWithEngine:aEngine data:data scriptName:aFileName];
}

- initWithEngine:(CSScriptEngine *)aEngine data:(NSData *)someData scriptName:(NSString *)aScriptName
{
    engine = [aEngine retain];
    name = [aScriptName retain];
    
    content = [someData retain];
    
    return self;
}

- (void)dealloc
{
    [engine release];
    [name release];
    [handle release];
    
    [super dealloc];
}

- (id)run
{
    v8::Handle<v8::Context> context = v8::Context::New(NULL,[[engine globalTemplate] handle]);
    v8::Context::Scope context_scope(context);
    return [self _run];
}

- (id)run:(NSString *)functionName
{
    return [self run:functionName arguments:nil];
}

- (id)run:(NSString *)functionName arguments:(NSArray *)arguments
{
    v8::Handle<v8::Context> context = v8::Context::New(NULL,[[engine globalTemplate] handle]);
    v8::Context::Scope context_scope(context);
    
    [self _run];
    v8::Local<v8::Function> fun = v8::Local<v8::Function>::Cast(context->Global()->Get(v8::String::New([functionName UTF8String])));
    
    if (fun.IsEmpty() || fun->IsUndefined()) {
        [NSException raise:@"CSJavaScriptException" format:@"Function [%@] not found", functionName];        
    }
    v8::Handle<v8::Value> args[24];
    for (int i= 0;i  < [arguments count];i++) {
        args[i] = convertObjCObjectToV8([arguments objectAtIndex:i]);
    }
    v8::TryCatch try_catch;
    v8::Local<v8::Value> result = fun->Call(fun, [arguments count], args);
    if (result.IsEmpty()) {
        v8::String::AsciiValue error(try_catch.Exception());
        [NSException raise:@"CSJavaScriptException" format:@"Runtime error [%s] on line [%d]", *error, try_catch.Message()->GetLineNumber()];        
    }
    else 
    {
        if (!result->IsUndefined()) {
            return convertV8ToObjCObject(result, CSObject);
        }
        else {
            return nil;
        }
    }
    
    
    return nil;
}

@end
